package org.eenie.appseed.ui.splash

import android.content.Intent
import androidx.lifecycle.lifecycleScope
import dev.chrisbanes.insetter.Insetter
import dev.chrisbanes.insetter.windowInsetTypesOf
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import org.eenie.appseed.databinding.ActivitySplashBinding
import org.eenie.appseed.ui.main.MainActivity
import org.eenie.core.base.viewbinding.BaseBindingActivity
import org.eenie.core.ext.onClick

import org.eenie.core.utils.TimerVm

class SplashActivity : BaseBindingActivity<ActivitySplashBinding>() {


    override fun initUI() {
        val vm: TimerVm = defaultViewModelProviderFactory.create(TimerVm::class.java)

        Insetter.builder()
            .marginTop(windowInsetTypesOf(statusBars = true))
            .applyToView(this.binding.tvCount)

        lifecycleScope.launch {
            vm.timerStateFlow.collectLatest {
                if (it.secondsRemaining != null && it.secondsRemaining!! <= 0) {
                    println(it.secondsRemaining)
                    startMainUi()
                } else {
                    this@SplashActivity.binding.tvCount.text = "跳过(${it.secondsRemaining ?: 0})"
                }
            }
        }


        this.binding.tvCount.onClick {
            startMainUi()
        }

        vm.toggleStart(3)
    }


    private fun startMainUi() {
        startActivity(Intent(mContext, MainActivity::class.java))
        finish()
    }

    override fun providerBinding() = ActivitySplashBinding.inflate(layoutInflater)


}